package com.own.demo.geodemo;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;


import java.util.ArrayList;
import java.util.List;

public class ToGeoJSON {
    static int HEIGHT = 10;
    static int AREA=3;

    @SneakyThrows
    public static String goGeoJSON(List<Geometry> geometries) {
        if (geometries == null) {
            return null;
        }

//        geometries=  geometries.subList(1,4);
//        SimpleFeatureType pointType = DataUtilities.createType("MultiPolygon", "geometry:MultiPolygon");
        int row = geometries.size();
//        GeometryFactory geometryFactory = new GeometryFactory();
//        List polygons=new ArrayList(row);
//        for(int i=0;i<row;i++){
//            Polygon geometry=(Polygon)geometries.get(i);
//            polygons.add(geometry);
//        }
////        MultiPolygon multiPolygon = geometryFactory.createMultiPolygon(polygons);
//
////        System.out.println(multiPolygon.toString());
//        SimpleFeature feature = SimpleFeatureBuilder.build(pointType, polygons, null);
//        FeatureJSON featureJSON = new FeatureJSON();
//        String geoJson = featureJSON.toString(feature);
//        System.out.println(geoJson);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "GeometryCollection");

        JSONArray jsonArray = new JSONArray(1024);
        for(int j=0;j<AREA;j++) {
            for (int i = 0; i < row; i++) {
                JSONObject geo = new JSONObject(4);
                Geometry js = geometries.get(i);
                geo.put("type", "Polygon");
                Coordinate[] coordinates = js.getCoordinates();
                int coordRow = coordinates.length;
                List<double[]> gpsList = new ArrayList<>(coordRow);

                for (int h = 0; h < coordRow; h++) {
                    Coordinate coordinate = coordinates[h];
                    double[] gps = new double[3];
                    gps[0] = coordinate.x;
                    gps[1] = coordinate.y;
                    gps[2] = HEIGHT*j;
                    gpsList.add(gps);
                }
                geo.put("coordinates", gpsList);
                geo.put("name", i > 0 ? i + "" : "area");
                jsonArray.add(geo);
            }
        }
        jsonObject.put("geometries", jsonArray);



        return JSONObject.toJSONString(jsonObject);
    }
}
